package com.hifar.test.standardbase.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.hifar.common.QueryParamBean;
import com.hifar.log.AutoLogUtils;
import com.hifar.model.BaseModel;
import com.hifar.model.VO.QueryParamsVO;
import com.hifar.test.standardbase.pojo.HfResStandard;
import com.hifar.test.standardbase.pojo.VO.HfResStandardSaveVO;
import com.hifar.test.standardbase.pojo.VO.HfResStandardVO;
import com.hifar.test.standardbase.service.IHfResStandardService;
import com.hifar.validate.CreateGroup;
import com.hifar.validate.UpdateGroup;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hifar.plat.baseModal.pojo.BaseOssFiles;
import com.hifar.plat.baseModal.service.IBaseOssFilesService;
import com.hifar.plat.officUtil.ExcelTemplateUtil;
import com.hifar.sys.BusiResponse;
import com.hifar.sys.MinioUtil;
import com.hifar.sys.PageResult;
import com.hifar.sys.RequestConver;
import com.hifar.sys.SystemLoginUser;
import com.hifar.sys.SystemUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * <p>
 * 资源-方法 前端控制器 default
 * </p>
 *
 * @author wangkepeng
 * @since 2024-12-12 10:49:33
 */
@RestController
@RequestMapping("/api/busi/test/hfResStandardController")
@Api(tags = "资源-方法功能")
public class HfResStandardController {

    @Autowired
    private IHfResStandardService hfResStandardService;

    @Autowired
    private IBaseOssFilesService baseOssFilesService;

    @Autowired
    private AutoLogUtils autoLogUtils;

    @PostMapping(value = "/list")
    @ApiOperation(value = "资源-方法功能:分页查询列表")
    public BusiResponse list(@RequestBody QueryParamsVO queryParamsVO) {
        QueryParamBean<HfResStandard> queryParamBean = new QueryParamBean<>(queryParamsVO, HfResStandard.class);
        QueryWrapper<HfResStandard> queryWrapper = queryParamBean.getQueryWrapper();
        Page<HfResStandard> page = queryParamBean.getPage();
        queryWrapper.orderByDesc("create_time");
        queryWrapper.in("secret_level", SystemLoginUser.dataSecretSet);
        Page<HfResStandard> pageData = hfResStandardService.page(page, queryWrapper);


        Page<HfResStandardVO> newPageData = new Page<>();

        BeanUtils.copyProperties(pageData, newPageData);

        List<HfResStandard> records = page.getRecords();
        List<HfResStandardVO> newRecords = new ArrayList<>(records.size());
        if (records.isEmpty()) {
            PageResult pageResult = SystemUtil.parsePage(page, pageData);
            return BusiResponse.OK(pageResult);
        }
        List<String> idList = records.stream()
                .map(BaseModel::getId)
                .collect(Collectors.toList());
        Map<String, Integer> standardFileNumMap = baseOssFilesService.queryFileNum(idList, "hf_res_standard");

        for (HfResStandard hfResStandard : records) {
            String id = hfResStandard.getId();
            HfResStandardVO hfResStandardVO = new HfResStandardVO();
            BeanUtils.copyProperties(hfResStandard, hfResStandardVO);
            Integer attachNum = standardFileNumMap.getOrDefault(id, 0);
            hfResStandardVO.setAttachNum(attachNum);
            newRecords.add(hfResStandardVO);
        }

        newPageData.setRecords(newRecords);

        PageResult pageResult = SystemUtil.parsePage(page, newPageData);
        return BusiResponse.OK(pageResult);
    }

    @PostMapping(value = "/listAll")
    @ApiOperation(value = "资源-方法功能:查询列表(不带分页)")
    public BusiResponse listAll(HttpServletRequest request) {
        QueryWrapper<HfResStandard> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("create_time");
        queryWrapper.in("secret_level", SystemLoginUser.dataSecretSet);
        List<HfResStandard> list = hfResStandardService.list(queryWrapper);
        return BusiResponse.OK(list);
    }

    @PostMapping(value = "/add")
    @ApiOperation(value = "资源-方法功能:新增")
    public BusiResponse add(@RequestBody @Validated(CreateGroup.class) HfResStandardSaveVO hfResStandardSaveVO) {
        //判断编号是否重复
        QueryWrapper<HfResStandard> queryWrapper = new QueryWrapper<>();
        String standardCode = hfResStandardSaveVO.getStandardCode();
        queryWrapper.eq("standard_code", standardCode);
        int count = hfResStandardService.count(queryWrapper);
        if (count > 0) {
            return BusiResponse.error(400, String.format("编码%s已经存在！", hfResStandardSaveVO.getStandardCode()));
        }
        HfResStandard hfResStandard = new HfResStandard();
        BeanUtils.copyProperties(hfResStandardSaveVO, hfResStandard);
        hfResStandardService.save(hfResStandard);
        String id = hfResStandard.getId();

        List<BaseOssFiles> files = hfResStandardSaveVO.getFiles();
        for (BaseOssFiles baseOssFiles : files) {
            baseOssFiles.setRefId(id);
            baseOssFiles.setRefType("hf_res_standard");
        }
        UpdateWrapper<BaseOssFiles> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda()
                .set(BaseOssFiles::getRefId, null)
                .eq(BaseOssFiles::getRefId, id)
                .eq(BaseOssFiles::getRefType, "hf_res_standard");
        baseOssFilesService.update(updateWrapper);
        baseOssFilesService.updateBatchById(files);
        autoLogUtils.addLog("环境试验-依据标准", String.format("新增依据标准:【%s】", standardCode));
        return BusiResponse.ok("添加成功");
    }


    @PostMapping(value = "/edit")
    @ApiOperation(value = "资源-方法功能:编辑")
    public BusiResponse edit(@RequestBody @Validated(UpdateGroup.class) HfResStandardSaveVO hfResStandardSaveVO) {

        String id = hfResStandardSaveVO.getId();

        //判断编号是否重复
        QueryWrapper<HfResStandard> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .ne(HfResStandard::getId, hfResStandardSaveVO.getId());
        String standardCode = hfResStandardSaveVO.getStandardCode();

        queryWrapper.eq("standard_code", standardCode);
        int count = hfResStandardService.count(queryWrapper);
        if (count > 0) {
            return BusiResponse.error(400, String.format("编码%s已经存在！", hfResStandardSaveVO.getStandardCode()));
        }

        HfResStandard hfResStandard = new HfResStandard();
        BeanUtils.copyProperties(hfResStandardSaveVO, hfResStandard);
        hfResStandardService.updateById(hfResStandard);

        List<BaseOssFiles> files = hfResStandardSaveVO.getFiles();
        for (BaseOssFiles baseOssFiles : files) {
            baseOssFiles.setRefId(id);
            baseOssFiles.setRefType("hf_res_standard");
        }
        UpdateWrapper<BaseOssFiles> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda()
                .set(BaseOssFiles::getRefId, null)
                .eq(BaseOssFiles::getRefId, id)
                .eq(BaseOssFiles::getRefType, "hf_res_standard");
        baseOssFilesService.update(updateWrapper);
        baseOssFilesService.updateBatchById(files);
        autoLogUtils.modifyLog("环境试验-依据标准", String.format("编辑依据标准:【%s】", standardCode));
        return BusiResponse.ok("编辑成功！");
    }


    @GetMapping("/queryById")
    @ApiOperation(value = "资源-方法功能:根据id查询数据")
    public BusiResponse queryById(@RequestParam(name = "id") String id) {
        HfResStandard hfResStandard = hfResStandardService.getById(id);
        Assert.notNull(hfResStandard, "数据不存在!");

        HfResStandardSaveVO hfResStandardSaveVO = new HfResStandardSaveVO();

        BeanUtils.copyProperties(hfResStandard, hfResStandardSaveVO);
        List<BaseOssFiles> baseOssFilesList = MinioUtil.listByRefId(id, "hf_res_standard");
        hfResStandardSaveVO.setFiles(baseOssFilesList);
        // 查询转换附件
        return BusiResponse.OK(hfResStandardSaveVO);
    }


    @PostMapping("/delete")
    @ApiOperation(value = "资源-方法功能:逻辑删除")
    public BusiResponse delete(@RequestBody List<String> idList) {
        List<HfResStandard> standardList = hfResStandardService.listByIds(idList);

        hfResStandardService.removeByIds(idList);
        String standardNames = standardList.stream()
                .map(HfResStandard::getStandardCode)
                .distinct()
                .collect(Collectors.joining(","));
        autoLogUtils.deleteLog("环境试验-依据标准", String.format("删除了依据标准:【%s】", standardNames));
        return BusiResponse.ok("删除成功！");
    }

    @PostMapping("/exportExcel")
    @ApiOperation(value = "资源-方法功能:导出数据")
    public Object exportExcel(HttpServletRequest request) {
        Map<String, Object> pageInfo = RequestConver.getPageInfo(request);
        if (pageInfo == null) {
            return BusiResponse.error(400, "参数有误！");
        }
        BusiResponse export = hfResStandardService.exportExcel(pageInfo);
        if (export.getCode() == com.hifar.fw.utils.bean.BusiConst.CODE_SUCCESS) {
            String encode = null;
            try {
                encode = URLEncoder.encode("资源-方法.xlsx", "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            HttpHeaders headers = new HttpHeaders();
            headers.add("Content-Type", "application/vnd.ms-excel");
            headers.add("Access-Control-Expose-Headers", "Content-Disposition");
            headers.add("Content-Disposition", "filename=" + encode);

            autoLogUtils.exportLog("环境试验-依据标准", "导出依据标准列表");
            return ResponseEntity.status(HttpStatus.OK).headers(headers).body((byte[]) export.getData());
        }
        return export;
    }

    @PostMapping("/importExcel")
    @ApiOperation(value = "资源-方法功能:导入excel数据")
    public BusiResponse importExcel(@RequestParam("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            return BusiResponse.error(400, "文件为空！");
        } else {
            if (ExcelTemplateUtil.isExcelFile(file)) {
                autoLogUtils.importLog("环境试验-依据标准", "导入依据标准列表");
                return hfResStandardService.importExcel(file);
            } else {
                return BusiResponse.error(400, "请上传excel文件！");
            }
        }
    }


}